package com.guoranhao.web.util.common;

import com.google.common.collect.Maps;
import com.guoranhao.contants.Constants;
import com.guoranhao.tool.utils.HttpUtils;
import com.guoranhao.tool.utils.JsonUtil;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;

/**
 * Created by Administrator on 2016/6/17 0017.
 */
public class WinxinUtil {

   private static Logger logger = LoggerFactory.getLogger(WinxinUtil.class);

   public static String appid= Constants.WX_APPID;
   public static  String appscret=Constants.WX_SECRET;
    public  static String getNewAccessToken() {
        String token = null;
        String requestUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET".replace("APPID",appid ).replace("APPSECRET", appscret);
        JSONObject jsonObject = WxstoreUtils.httpRequest(requestUrl, "GET", null);
        if (null != jsonObject) {
            try {
                token = jsonObject.getString("access_token");
            } catch (Exception e) {
                token = null;
            }
        }
        logger.info("token is : {} ", token);
        return token;
    }


    public static String getTicket(String access_token) {
        String ticket = null;

        String url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token="+ access_token +"&type=jsapi";
        JSONObject jsonObject = WxstoreUtils.httpRequest(url, "GET", null);
        if (null != jsonObject) {
            try {
                ticket = jsonObject.getString("ticket");
            } catch (Exception e) {
                ticket = null;
            }
        }

        return ticket;
    }
    
    @SuppressWarnings("unchecked")
	public  static Map<String, Object> getNewAccessTokenByAppId(String url,String appId, String secret) {
        String requestUrl = url.replace("APPID",appId ).replace("APPSECRET", secret);
        String response = HttpUtils.requestGet(requestUrl, null);
        Map<String, Object> data = Maps.newHashMap();
        if (StringUtils.isNotBlank(response)) {
            data = JsonUtil.Json2Object(response, Map.class);
        }        
 
        return data;
    }
    public static void main(String[]args){

      //  System.out.println(getNewAccessToken());
     System.out.println(getTicket(getNewAccessToken()));
    }
}
